<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020-02-25
 * Time: 11:52
 */

namespace Zwwl2016\Cluster;


class ClusterService
{
    private $cluster;
    private $serviceKey;
    private $clusterParameters;
    private $responce;
    private $async=true;
    public function __construct(Cluster $cluster,$serviceKey)
    {
        $this->cluster=$cluster;
        $this->serviceKey=$serviceKey;
        $this->clusterParameters=ClusterParameters::Instance();
    }

    /**
     * @param ClusterCronTaskParameters $cronTaskParameters use ClusterCronTaskParameters.Instance() to create
     * @return ClusterService 绑定本服务到计划任务,返回执行结果。
     */
    public function bindClusterCronTasks(ClusterCronTaskParameters $cronTaskParameters)
    {
        $obj=new \stdClass();
        $parameterList=$cronTaskParameters->getArray();
        $obj->parameters=$parameterList;
        $arr=$this->cluster->execute( $this->serviceKey,"cron-task", $obj, false);
        $this->responce=$arr;
        return $this;
    }

    /**
     * @param ClusterParameters $item
     * @return ClusterService 设置服务参数
     */
    public function setParameters(ClusterParameters $item)
    {
        $this->clusterParameters=$item;
        return $this;
    }

    /**
     * @return $this 启动服务
     */
    public function start()
    {
        $this->responce=$this->cluster->execute($this->serviceKey, "service", $this->clusterParameters->getArray(), $this->async);
        return $this;
    }

    /**
     * @return ClusterService 设置启动方式为异步(默认为异步)
     */
    public function async()
    {
        $this->async=true;
        return $this;
    }

    /**
     * @return ClusterService 设置启动方式为同步(默认为异步)
     */
    public function sync()
    {
        $this->async=false;
        return $this;
    }

    /**
     * @return string 返回start执行后的结果
     */
    public function response()
    {
        return $this->responce;
    }

}